//
#include "tsp.h"
#include <iostream>
#include <thread>

PC::PC(
    const std::string& topicAddr_, const std::string& topicName_,
    const std::string& pushAddr
) : topicAddr(topicAddr_), topicName(topicName_), push_address(pushAddr) {
    sub = zmq::socket_t(ctx, zmq::socket_type::sub);
    sub.connect(topicAddr.c_str());
    sub.set(zmq::sockopt::subscribe, topicName);
    //
    push_socket = zmq::socket_t(ctx, zmq::socket_type::push);
    push_socket.bind(push_address);
}

PC::~PC() {
}

void PC::startup() {
    zmq::message_t msgTopicName;
    zmq::message_t msgData;
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        if (!sub.recv(msgTopicName, zmq::recv_flags::none)) {
            std::cerr << "Subscribe: Failed to receive topic name" << std::endl;
            continue;
        }
        std::string topicName_(static_cast<char*>(msgTopicName.data()), msgTopicName.size());
        if (!sub.recv(msgData, zmq::recv_flags::none)) {
            std::cerr << "Subscribe: Failed to receive data" << std::endl;
            continue;
        }
        uint8_t *ptr = reinterpret_cast<uint8_t*>(msgData.data());
        auto signal = std::vector<uint8_t>(ptr, ptr+msgData.size());
        std::cout << "脉冲压缩: " << signal[0] << ", " << signal[1] << "; !!!!!!!" << std::endl;
        // 向MTI发送数据
        uint8_t output[1024];
        output[0] = 97;
        output[1] = 98;
        zmq::message_t response(sizeof(uint8_t) * 1024);
        memcpy(response.data(), output, sizeof(uint8_t) * 1024);
        try {
            push_socket.send(response, zmq::send_flags::none);
        } catch (const zmq::error_t& e) {
            std::cerr << "ZMQ error: " << e.what() << std::endl;
            break;
        }
    }
}